package com.rchat.pocmini.activity.main;

import android.content.Intent;
import android.media.AudioManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.airtalkee.sdk.AirtalkeeMediaAudioControl;
import com.aso.common.utils.NetworkUtils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.fragment.FriendFragment;
import com.rchat.pocmini.activity.fragment.groups.GroupsFragment;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.common.mvp.BaseMvpActivity;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by itsdf07 on 2017/7/25.
 */
public class MainActivity extends BaseMvpActivity<MainPresenterImpl, MainModelImpl>
        implements MainContract.View {

    /**
     * 群组
     */
    private final int TAB_GROUP = 0;
    /**
     * 好友
     */
    private final int TAB_FRIENDS = 1;

    private long mExitTime = 0;

    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager mFragmentManager;
//    private FragmentTransaction mTransaction;

    private GroupsFragment mGroupsFragment;
    private FriendFragment mFriendFragment;

    @BindView(R.id.framelayout_content)
    FrameLayout mFramelayoutContent;
    @BindView(R.id.btn_group)
    TextView mBtnGroup;
    @BindView(R.id.btn_friends)
    TextView mBtnFriends;
    @BindView(R.id.btn_ptttalk)
    ImageView mBtnPttTalk;

    @Override
    public void initPresenter() {
        mFragmentManager = getSupportFragmentManager();
        mPresenter.setVM(this, mModel);
        mPresenter.initJPush();


    }

    @Override
    public int getLayoutId() {
        return R.layout.main_activity;
    }

    @Override
    public void initView() {
        showFragments(TAB_GROUP);
        mBtnPttTalk.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    mPresenter.pttTalkRelease();
                    mBtnPttTalk.setImageResource(R.drawable.ic_location_talk);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (!NetworkUtils.isConnected()) {
                        showNetError();
                        return true;
                    }
                    mBtnPttTalk.setImageResource(R.drawable.ic_location_talk_pressed);
                    mPresenter.pttTaklRequest();
                }
                return true;
            }
        });
    }

    @Override
    public void doAfterInitView() {
        //=======启动音乐播放，在华为机型上保活应用=======//
//        Log.e("startPlayMusic","startService");
//        Intent musicIntent = new Intent();
//        musicIntent.setClass(this,PlayerMusicService.class);
//        startService(musicIntent);


        //蓝牙声音不一致问题
        AirtalkeeMediaAudioControl.getInstance().setStreamType(AudioManager.STREAM_VOICE_CALL);
        //启动友盟账号统计
        MobclickAgent.onProfileSignIn(PocAccount.getUserId());
        mPresenter.queryJPushMessage();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String groupId = getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        ALog.d("onNewIntent del GroupId = %s", groupId);
        mGroupsFragment.doDeleteGroup(groupId);
    }

    @OnClick({R.id.btn_group, R.id.btn_friends})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_group:
                showFragments(TAB_GROUP);
                break;
            case R.id.btn_friends:
                showFragments(TAB_FRIENDS);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this, "再按一次应用将退到后台运行", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            moveTaskToBack(true);
        }
    }

    /**
     * 显示Fragment
     * PS:显示之前，先做全部的Fragment隐藏
     *
     * @param tab
     */
    private void showFragments(int tab) {
        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
        hideFragments(tab, mTransaction);
        if (TAB_GROUP == tab) {
            if (null == mGroupsFragment) {
                mGroupsFragment = new GroupsFragment();
                mTransaction.add(R.id.framelayout_content, mGroupsFragment);
            } else {
                mTransaction.show(mGroupsFragment);
            }
        } else if (TAB_FRIENDS == tab) {
            if (null == mFriendFragment) {
                mFriendFragment = new FriendFragment();
                mTransaction.add(R.id.framelayout_content, mFriendFragment);
            } else {
                mTransaction.show(mFriendFragment);
            }
        }

        mTransaction.commit();
        updateNavigationBtnStatus(tab);
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param tab
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(int tab, FragmentTransaction transaction) {
        if (null == mGroupsFragment) {
            mGroupsFragment = new GroupsFragment();
            transaction.add(R.id.framelayout_content, mGroupsFragment);
        }
        if (null == mFriendFragment) {
            mFriendFragment = new FriendFragment();
            transaction.add(R.id.framelayout_content, mFriendFragment);
        }

//        if (TAB_GROUP == tab) {
        transaction.hide(mFriendFragment);
//        } else {
        transaction.hide(mGroupsFragment);
//        }
    }

    /**
     * 更新导航栏按钮的选中态
     *
     * @param currentTab 当前tab页
     */
    private void updateNavigationBtnStatus(int currentTab) {
        ALog.d("currentTab = %s", currentTab);
        mBtnGroup.setSelected(TAB_GROUP == currentTab);
        mBtnFriends.setSelected(TAB_FRIENDS == currentTab);
    }

}
